package com.woniuxy.interceptor;

import com.alibaba.fastjson.JSON;
import com.woniuxy.anno.PreAuthorize;
import com.woniuxy.mapper.MenuMapper;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import com.woniuxy.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * @author dingpf
 * @version 1.0
 * @description
 * @create 2024/8/26 11:21
 */
@Component
public class AuthrizaIntecepter implements HandlerInterceptor {

    @Autowired
    private MenuMapper menuMapper;


    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //从request获取当前登录用户id,没有登录模拟获取到用户Id
        System.out.println("now join in AuthrizaIntecepter");
        Long userId = UserContext.getUserId();


        //根据用户的id查询当前登录用户的权限code
        List<String> authcode = menuMapper.queryPowerUserAuthByUserId(userId.intValue());
        if (handler instanceof HandlerMethod) {//确认访问的是否是controller里面的方法
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();//获取用户正在访问的方法的对象
            PreAuthorize preAuthorize = method.getAnnotation(PreAuthorize.class);//获取这个方法上的PreAuthorize注解
            if (preAuthorize != null) {//表示这个方法上真的有PreAuthorize这个注解
                String[] AuthArr = preAuthorize.value();//获取这个注解上面填写的
                //当前登录用户的权限，是否在这个AuthArr数组中,在表示有权限，不在就响应无权限
                boolean b = Arrays.stream(AuthArr).anyMatch(s -> authcode.contains(s));
                if (!b) {
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(JSON.toJSONString(new ResponseData<>().fail(ResponseEnum.NO_PERMISSION)));
                    return false;
                }
            }
        }

        return true;
    }
}
